package com.qingcheng.timer;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGoods;
import com.qingcheng.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * 定时执行 类
 *
 * @author 岳剑飞
 * @Company http://www.ithiema.com
 */
@Component
public class SeckillGoodsPushTask {

    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 每30秒执行一次
     * 将参与秒杀活动的数据压入缓存中
     */
    @Scheduled(cron = "0/30 * * * * ?  ")
    public void loadGoodsPushRedis() {
        System.out.println("task demo ......");

        //获取时间段集合
        List<Date> dateMenus = DateUtil.getDateMenus();
        //循环遍历时间段
        for (Date startTime : dateMenus) {
            //时间转成yyyyMMddHH   2019082420
            String extName = DateUtil.date2Str(startTime);

            //根据时间段查询对应的秒杀商品数据
            Example example = new Example(SeckillGoods.class);
            Example.Criteria criteria = example.createCriteria();
            //1) 商品必须审核通过. status=1
            criteria.andEqualTo("status", "1");
            //2) 库存>0
            criteria.andGreaterThan("stockCount", 0);
            //3. 开始时间<=活动开始时间
            criteria.andGreaterThanOrEqualTo("startTime", startTime);
            //4. 活动结束时间<开始时间+2
            criteria.andLessThan("endTime", DateUtil.addDateHour(startTime, 2));
            //5. 排除之前已经加载到redis 缓存中的商品数据
            Set keys = redisTemplate.boundHashOps("SeckillGoods_" + extName).keys(); //SeckillGoods_2019082420
            if (keys != null && keys.size() > 0) {
                criteria.andNotIn("id", keys);
            }

            //查询数据
            List<SeckillGoods> seckillGoods = seckillGoodsMapper.selectByExample(example);

            //  将秒杀商品数据存入到Redis缓存
            for (SeckillGoods seckillGood : seckillGoods) {
                System.out.println(seckillGood);
                redisTemplate.boundHashOps("SeckillGoods_" + extName).put(seckillGood.getId(),seckillGood);
            }

        }

    }
}
